{% include 'java.header.j2' %}

package com.beracash.mch.ctrl.{{ table.mark.business_name }};

import com.beracash.common.ctrl.CommonCtrl;
import com.beracash.core.constants.ApiCodeEnum;
import com.beracash.core.model.ApiRes;
import {{ table.mark.package }}.{{ table.mark.business_name }}.{{ table.derived.naming.class_name }};
import {{ table.mark.package }}.{{ table.mark.business_name }}.{{ table.derived.naming.service_name }};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/anon/{{ table.mark.business_name }}")
public class {{ table.derived.naming.controller_name }} extends CommonCtrl {

    private static final Logger log = LoggerFactory.getLogger({{ table.derived.naming.controller_name }}.class);

    @Autowired
    private {{ table.derived.naming.service_name }} {{ table.mark.business_name }}Service;

    // 获取{{ table.common.label }}列表（支持分页和条件查询）
    @GetMapping
    public ApiRes<Page<{{ table.derived.naming.class_name }}>> list(@RequestParam(required = false, defaultValue = "1") int pageNumber
                                   , @RequestParam(required = false, defaultValue = "10") int pageSize
                                   {%- for field_name, field in columns.items() -%}
                                   {%- if field.mark.searchable is defined and field.mark.searchable.type in ['like', 'equal'] %}
                                   , @RequestParam(required = false) String {{ field.naming.field_name }}
                                   {%- endif -%}
                                   {%- endfor %}
                                   ) {
        log.info("=== {{ table.common.label }} 分页请求开始 ===");
        log.info("请求参数: pageNumber={}, pageSize={}", pageNumber, pageSize);

        QueryWrapper<{{ table.derived.naming.class_name }}> queryWrapper = new QueryWrapper<>();

        // 只有当参数不为空且不为空字符串时才添加条件
        {%- for field_name, field in columns.items() -%}
        {%- if field.mark.searchable is defined %}
        {%- if field.mark.searchable.type == 'like' %}
        if (StringUtils.isNotBlank({{ field.naming.field_name }})) {
            queryWrapper.like("{{ field.sql.name }}", {{ field.naming.field_name }});
        }
        {%- elif field.mark.searchable.type == 'equal' %}
        if (StringUtils.isNotBlank({{ field.naming.field_name }})) {
            queryWrapper.eq("{{ field.sql.name }}", {{ field.naming.field_name }});
        }
        {%- endif -%}
        {%- endif -%}
        {%- endfor %}

        Page<{{ table.derived.naming.class_name }}> newPage = new Page<>(pageNumber, pageSize);
        Page<{{ table.derived.naming.class_name }}> resultPage = (Page<{{ table.derived.naming.class_name }}>) {{ table.mark.business_name }}Service.selectPage(newPage, queryWrapper);

        log.info("分页查询结果: total={}, current={}, size={}, records.size={}",
                 resultPage.getTotal(), resultPage.getCurrent(),
                 resultPage.getSize(), resultPage.getRecords().size());
        log.info("=== {{ table.derived.naming.class_name }} 分页请求结束 ===");

        return ApiRes.ok(resultPage);
    }

    // 添加新{{ table.common.label }}
    @PostMapping
    public ApiRes<Void> add(@RequestBody {{ table.derived.naming.class_name }} record) {
        // 设置必要的默认值
        {%- for field_name, field in columns.items() -%}
        {%- if not field.sql.nullable %}
        if (record.{{ field.derived.java.getter }}() == null) {
            record.{{ field.derived.java.setter }}({{ field.derived.java.default_value }}); // 默认{{ field.common.label }}
        }
        {%- endif -%}
        {%- endfor %}

        {{ table.mark.business_name }}Service.insert(record);
        return ApiRes.ok();
    }

    // 获取{{ table.common.label }}详情
    @GetMapping("/{recordId}")
    public ApiRes<{{ table.derived.naming.class_name }}> detail(@PathVariable {{ table.derived.java.primary_key_java_type }} recordId) {
        {{ table.derived.naming.class_name }} record = {{ table.mark.business_name }}Service.selectById(recordId);
        if (record == null) {
            return ApiRes.fail(ApiCodeEnum.CUSTOM_FAIL, "{{ table.derived.naming.class_name }} not found");
        }
        return ApiRes.ok(record);
    }

    // 更新{{ table.common.label }}信息
    @PutMapping("/{recordId}")
    public ApiRes<Void> update(@PathVariable {{ table.derived.java.primary_key_java_type }} recordId, @RequestBody {{ table.derived.naming.class_name }} record) {
        record.setId(recordId);
        {{ table.mark.business_name }}Service.updateById(record);
        return ApiRes.ok();
    }

    // 删除{{ table.common.label }}
    @DeleteMapping("/{recordId}")
    public ApiRes<Void> delete(@PathVariable {{ table.derived.java.primary_key_java_type }} recordId) {
        {{ table.mark.business_name }}Service.deleteById(recordId);
        return ApiRes.ok();
    }

    // 批量删除{{ table.common.label }}
    @DeleteMapping
    public ApiRes<Void> deleteBatch(@RequestBody List<{{ table.derived.java.primary_key_java_type }}> ids) {
        {{ table.mark.business_name }}Service.deleteBatchIds(ids);
        return ApiRes.ok();
    }

    // 根据条件查询{{ table.common.label }}
    @PostMapping("/search")
    public ApiRes<List<{{ table.derived.naming.class_name }}>> search(@RequestBody Map<String, Object> queryMap) {
        QueryWrapper<{{ table.derived.naming.class_name }}> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap);
        List<{{ table.derived.naming.class_name }}> list = {{ table.mark.business_name }}Service.selectList(queryWrapper);
        return ApiRes.ok(list);
    }

    // 获取{{ table.common.label }}数量
    @GetMapping("/count")
    public ApiRes<Long> count(@RequestParam Map<String, Object> queryMap) {
        QueryWrapper<{{ table.derived.naming.class_name }}> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap);
        Long count = {{ table.mark.business_name }}Service.selectCount(queryWrapper);
        return ApiRes.ok(count);
    }

    // 获取{{ table.common.label }}的 Map 数据
    @GetMapping("/maps")
    public ApiRes<List<Map<String, Object>>> listMaps(@RequestParam Map<String, Object> queryMap) {
        QueryWrapper<{{ table.derived.naming.class_name }}> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap);
        List<Map<String, Object>> maps = {{ table.mark.business_name }}Service.selectMaps(queryWrapper);
        return ApiRes.ok(maps);
    }

    // 分页查询{{ table.common.label }}的 Map 数据
    @GetMapping("/mapsPage")
    public ApiRes<Page<Map<String, Object>>> listMapsPage(@RequestParam int page,
                                                          @RequestParam int size,
                                                          @RequestParam Map<String, Object> queryMap) {
        QueryWrapper<{{ table.derived.naming.class_name }}> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(queryMap);
        Page<Map<String, Object>> mapPage = new Page<>(page, size);
        Page<Map<String, Object>> resultPage = (Page<Map<String, Object>>) {{ table.mark.business_name }}Service.selectMapsPage(mapPage, queryWrapper);
        return ApiRes.ok(resultPage);
    }
}
